package com.moyo.repository;

import com.moyo.model.SysRolePermission;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 角色-权限关联数据访问（内存实现，后续可替换为JPA/MyBatis）
 */
public class SysRolePermissionRepository {
    private final Map<Long, SysRolePermission> rolePermissionMap = new HashMap<>();
    private final AtomicLong idGen = new AtomicLong(1);

    public SysRolePermission save(SysRolePermission rolePermission) {
        if (rolePermission.getId() == null) {
            rolePermission.setId(idGen.getAndIncrement());
        }
        rolePermissionMap.put(rolePermission.getId(), rolePermission);
        return rolePermission;
    }

    public Optional<SysRolePermission> findById(Long id) {
        return Optional.ofNullable(rolePermissionMap.get(id));
    }

    public List<SysRolePermission> findByRoleId(Long roleId) {
        return rolePermissionMap.values().stream()
                .filter(rp -> rp.getRoleId().equals(roleId))
                .collect(Collectors.toList());
    }

    public List<SysRolePermission> findByPermissionId(Long permissionId) {
        return rolePermissionMap.values().stream()
                .filter(rp -> rp.getPermissionId().equals(permissionId))
                .collect(Collectors.toList());
    }

    public void deleteByRoleIdAndPermissionId(Long roleId, Long permissionId) {
        rolePermissionMap.values().removeIf(rp -> 
            rp.getRoleId().equals(roleId) && rp.getPermissionId().equals(permissionId));
    }

    public void deleteByRoleId(Long roleId) {
        rolePermissionMap.values().removeIf(rp -> rp.getRoleId().equals(roleId));
    }

    public void deleteByPermissionId(Long permissionId) {
        rolePermissionMap.values().removeIf(rp -> rp.getPermissionId().equals(permissionId));
    }
} 